<template>
  <div>
    <div class="bgBackground" :style="background" style="overflow-y: auto;overflow-x: auto">
      <div style="width: 100%; height: 80px;display: inline-block;overflow-x: paged-x">
        <div style="float: left;margin-left: 5%" class="title_div">
          <h2 class="title_h2">
            <i class="el-icon-s-home"></i>
            弄个房租</h2>
        </div>
      </div>

      <div style="height: 500px;width: 500px;margin-left: 30%">
        <el-tabs v-model="activeName">
          <el-tab-pane label="登录" name="first">
            <el-form :model="loginInfoVo" ref="loginForm" size="medium" :inline="true" label-position="right">
              <el-form-item :rules="[{ required: true, message: '请输入用户名！', trigger: 'blur' }]" label="用户名:" style="margin-top: 30px">
                <el-input placeholder="请输入用户名或者邮箱账号" style="width: 400px;" prefix-icon="el-icon-user"
                          v-model="loginInfoVo.username"></el-input>
              </el-form-item>
              <el-form-item :rules="[{ required: true, message: '请输入密码！', trigger: 'blur' }]" label="密码  : " style="margin-top: 30px">
                <el-input placeholder="请输入密码" style="width: 400px;" prefix-icon="el-icon-key" type="password"
                          v-model="loginInfoVo.password"></el-input>
              </el-form-item>
              <el-form-item :rules="[{ required: true, message: '请输入验证码！', trigger: 'blur' }]" label="验证码:" style="margin-top: 30px">
                <el-input placeholder="请输入验证码" type="text" v-model="loginInfoVo.validate">
                  <img slot="append" @click="craeteValidate" :src="'data:image/png;base64,'+imageBase64" width="150"
                       height="32px">
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="login()" plain>确定</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="注册" name="second">
            <el-form ref="registerForm" :rules="rules" :model="RegisterInfoVo" size="medium" :inline="true">
              <el-form-item label-width="100px" label="用户名:" style="margin-top: 20px" prop="username">
                <el-input type="text" style="width: 380px;" placeholder="请输入用户名"
                          v-model="RegisterInfoVo.username"></el-input>
              </el-form-item>
              <el-form-item label-width="100px" label="密码:" style="margin-top: 20px" prop="password">
                <el-input style="width: 380px;" type="password" placeholder="请输入密码"
                          v-model="RegisterInfoVo.password"></el-input>
              </el-form-item>
              <el-form-item label-width="100px" label="确认密码：" style="margin-top: 20px" prop="rePassword">
                <el-input style="width: 380px;" type="password" placeholder="请确认密码"
                          v-model="RegisterInfoVo.rePassword"></el-input>
              </el-form-item>
              <el-form-item label-width="100px" prop="email"
                            label="邮箱"
                            :rules="[
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ]" style="margin-top: 20px">
                <el-input placeholder="请输入邮箱" style="width: 260px;" v-model="RegisterInfoVo.email"></el-input>
                <el-button type="primary" :disabled="BtnStatus" @click="getEmailValidate()" plain>
                  {{ !BtnStatus ? '获取验证码' : `${countDownTime}秒后获取` }}
                </el-button>
              </el-form-item>
              <el-form-item prop="emailValidate" :rules="[
      { required: true, message: '请输入验证码', trigger: 'blur' }]"
                            label-width="100px" label="验证码：" style="margin-top: 20px">
                <el-input placeholder="请输入验证码" style="width: 380px;" v-model="RegisterInfoVo.emailValidate"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="registerUser('registerForm')" plain>确定注册</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>


  </div>

</template>

<script>
import backImage from "../../static/image/loginBg.png";

export default {
  name: "LoginModle",
  data() {
    var validatePass = (rule, value, callback) => {
      const mailReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]/
      const mailReg1 = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (!mailReg.test(value)) {
        callback(new Error('密码需由数字和字母组成！'));
      } else if (!mailReg1.test(value)) {
        callback(new Error('密码长度在8位到16位之间！'));
      } else {
        if (this.RegisterInfoVo.rePassword !== '') {
          this.$refs.registerForm.validateField('rePassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.RegisterInfoVo.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    var username = (rule, value, callback) => {
      const mailReg1 = /.{6,12}$/
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else if (!mailReg1.test(value)) {
        callback(new Error('用户名长度需在6到20位之间！'));
      } else {
        callback();
      }
    };
    return {
      activeName: "first",
      countDownTime: 60,
      BtnStatus: false,
      loginInfoVo: {
        username: "",
        password: "",
        validate: "",
      },
      RegisterInfoVo: {
        username: "",
        password: "",
        rePassword: "",
        email: "",
        emailValidate: "",
      },
      imageBase64: '',
      validateCode: '',
      rules: {
        username: [
          {validator: username, trigger: 'blur', required: true}
        ],
        password: [
          {validator: validatePass, trigger: 'blur', required: true}
        ],
        rePassword: [
          {validator: validatePass2, trigger: 'blur', required: true}
        ],
      },
      background: {
        // 背景图片地址
        backgroundImage: `url(${backImage})`,
        width: '100%',
        height: '100%',
        position: 'fixed',
        // 背景图片是否重复
        backgroundRepeat: 'no-repeat',
        // 背景图片大小
        backgroundSize: '100% 100%',
        // 背景颜色
        backgroundColor: '#2b2b2b',
        // // 背景图片位置
        // backgroundPosition: 'center center',
      }
    }
  },
  created() {
    let myEndTime = localStorage.getItem('myEndTime')
    myEndTime && this.codeCountDown(myEndTime)
  },
  mounted() {
    this.craeteValidate()
  },
  methods: {
    //注册
    registerUser(formName) {
      let registerData = this.RegisterInfoVo

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios({
            method: "post",
            url: "/registerUser",
            params: {
              ...registerData,
              password: this.$md5(registerData.password),
              rePassword: ''
            }
          }).then(res => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.loginInfoVo.username = this.RegisterInfoVo.username
              this.loginInfoVo.password = this.RegisterInfoVo.password
              this.$refs[formName].resetFields()
              this.activeName = "first"
            } else {
              this.$message.error(res.data.message)
            }
          })

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //邮箱60秒倒计时
    codeCountDown(endMsRes) {
      this.BtnStatus = true;
      this.countDownTime = Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
      let time = setTimeout(() => {
        this.countDownTime--
        if (this.countDownTime < 1) {
          this.BtnStatus = false
          this.countDownTime = 60
          localStorage.removeItem('myEndTime')
          clearTimeout(time)
        } else {
          this.codeCountDown(endMsRes)
        }
      }, 1000)
    },
    //获取邮箱验证码
    getEmailValidate() {
      let email = this.RegisterInfoVo.email
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (mailReg.test(email)) {
        let endMsRes = (new Date()).getTime() + 60000;
        localStorage.setItem('myEndTime', JSON.stringify(endMsRes));
        this.BtnStatus = false;
        this.countDownTime = Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
        this.codeCountDown(endMsRes)

        this.$axios({
          method: "get",
          url: "/getEmailValidate",
          params: {
            email: email,
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
          } else {
            this.$message.error("请联系管理员！")
          }
        })
      }
    },
    //登录
    login() {
      let validateCode = this.loginInfoVo.validate
      let validate = this.$md5(validateCode)
      this.$refs['loginForm'].validate(validate1=>{
        if (validate1){
          if (validate !== this.validateCode) {
            this.$message.error("验证码不正确！")
          } else {
            this.$axios.post('/myLoginForm?userName=' + this.loginInfoVo.username + "&passWord=" + this.$md5(this.loginInfoVo.password))
              .then(res => {
                if (res.data.code === 200) {
                  let token = res.data.token;
                  window.localStorage.setItem("Authorization", token)
                  this.$router.push({path: "/"})
                } else {
                  this.$message.error(res.data.message)
                }
              })
          }
        }
      })

    },
    //获取图片验证码
    craeteValidate() {
      this.$axios({
        method: "get",
        url: "/getValidateCode",
      }).then(res => {
        if (res.data.code === 200) {
          this.imageBase64 = res.data.data.ImageBase64
          this.validateCode = res.data.data.codeMd5
        } else {

        }
      })
    }
  }
}
</script>

<style scoped>
.title_h2 {
  font-family: "Arial", "Microsoft YaHei", "黑体", "宋体", sans-serif;
  color: #55bd87;
}

.bgBackground {
  width: 100%;
  height: 500px
}

.title_div :hover{
  cursor: pointer;
}
</style>
